<?php
/**
 * 用户相关接口
 * 接受数据格式:POST
 * 返回数据格式:JSON
 * 
 * @author Wayne(wayneyu@flaringtech.com)
 * 
 */
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends Jiuchi_Controller {
	private $returnUrl;
	private $model;

    function __construct() {
        parent::__construct();
        $this->load->model('user_model');
		$this->load->model('user_concern_model');
		$this->load->model('user_dynamic_model');
		$this->load->model('topic_model');
    }
    
    /**
     * 用户登陆接口
     * 
     * 页面	:登陆页面
     * URL	:/user/login
     * 备注	:
     * 验证	:否
     * 接受参数:Username,Password
     * 返回参数:Token,UserID,Username,Telephone,HeadPortrait（头像url）,CarNo,Balance（余额），CouponCount（可用优惠券个数），MsgCount（消息个数）
     */
    function login(){
    	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	if(count($input) != 2 || !isset($input['Username']) || !isset($input['Password'])){
    		$this->apioutput->apiResponseError('接口参数不正确！');
    	}
		//初始化
		!empty($input['Username']) && ($input['Username'] = $this->varfilter->checkString($input['Username']));
		!empty($input['Password']) && ($input['Password'] = $this->varfilter->checkString($input['Password']));
     	
		if(empty($input['Username']) || empty($input['Password'])){
			$this->apioutput->apiResponseError('用户或密码不正确');
		}
		
		$userData = $this->user_model->getInfo($input['Username'], 'telephone');

		if(!($userData) || empty($userData)){
			$this->apioutput->apiResponseError('用户不存在');
		}
		
		if(md5(md5($input['Password']).$userData['salt']) != $userData['password']){
			$this->apioutput->apiResponseError('密码不正确');
		}
		
		if(!$this->user_model->checkUserStatus($userData['status'])){
			$this->apioutput->apiResponseError('用户未激活');
		}
		
		$this->mytoken->createToken();
		$this->load->driver('cache', array('adapter' => 'redis'));
		$cache = $this->cache->get('user_'.$userData['id']);
		if(empty($cache)){
			$this->cache->save('user_'.$userData['id'], $userData);
		}
		 
		$this->mytoken->set_userdata(array(
				'uid'		=> $userData['id'],
				'telephone'	=> $userData['telephone'],
				'nickname'	=> $userData['nickname']
		));
		
		
		//返回结果
		$results = array(
				'Token'		=> $this->mytoken->userdata('token'),
				'UserID'	=> $this->mytoken->userdata('uid'),
				'Username'	=> $this->mytoken->userdata('nickname'),
				'Telephone'	=> $this->mytoken->userdata('telephone'),
				'HeadPortrait'	=> site_url($userData['headportrait']),
				'Signature'	=> $userData['signature'],
				'School'	=> $userData['school'],
				'Department'=> $userData['department'],
				'Class'		=> $userData['class'],
				'Title'		=> $userData['title']
		);
		$this->apioutput->apiResponseSuccess($results, '登陆成功！');
    }
    
    /**
     * 用户登陆接口
     *
     * 页面	:登陆页面
     * URL	:/user/login
     * 备注	:
     * 验证	:是
     * 接受参数:
     * 返回参数:
     */
    function logout(){
    	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	if($input != null){
    		$this->error('接口参数不正确！');
    	}
    	$this->load->driver('cache', array('adapter' => 'redis'));
    	$this->cache->delete('user_'.$this->mytoken->userdata('uid'));
    	$this->mytoken->destroyToken();
    	$this->apioutput->apiResponseSuccess();
    }
    
    /**
     * 用户注册接口
     *
     * 页面	:用户注册页面3,用户修改密码
     * URL	:/user/changepwd
     * 备注	:
     * 验证	:否
     * 接受参数:Telephone,Password,Type
     * 返回参数:Token,UserID,Username,Telephone,HeadPortrait（头像url）,CarNo,Balance（余额），CouponCount（可用优惠券个数），MsgCount（消息个数）
     */
    function changepwd(){
	  	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	if(count($input) != 3 || !isset($input['Telephone']) || !isset($input['Password']) || !isset($input['Type'])){
    		$this->error('接口参数不正确！');
    	}
    	!empty($input['Password']) && ($input['Password'] = $this->varfilter->checkString($input['Password']));
    	if(empty($input['Password'])){
    		$this->error('密码不能为空');
    	}
    	switch ($input['Type']){
    		case 'Reg':
    			$count = 1;
    			$ret = $this->user_model->retrieve($count, NULL, NULL, NULL, array('telephone'=>$input['Telephone']));
    			if($ret != 0) {
    				$this->error('您输入的手机号已存在！');
    			}
    			
    			$userData['status']		= '1';
    			$userData['username']	= $this->generateUsername();
    			$userData['telephone']	= $input['Telephone'];
    			$userData['salt']		= substr(uniqid(rand()), -6);
    			$userData['password']	= md5(md5($input['Password']).$userData['salt']);
    			$userData['created_at']	= date('Y-m-d H:i:s');
    			$userData['updated_at'] = $userData['created_at'];
    			$authorization			= explode(',',$_SERVER['HTTP_AUTHORIZATION']);
    			$userData['login_device']	= $authorization[2];
    			
    			$this->{__CLASS__.'_model'}->begin();
    			$ret = $this->{__CLASS__.'_model'}->create($userData);
    			if($ret <= 0){
    				$this->{__CLASS__.'_model'}->rollback();
    				$this->error('系统忙，稍后再试');
    			}
    			$this->load->model('User_balance_model');
    			$balance = array(
    					'utype'=>1,
    					'uid'=>$ret,
    					'amount'=>0,
    					'created_at'=>$userData['updated_at'],
    					'updated_at'=>$userData['updated_at']
    			);
    			$ret = $this->User_balance_model->create($balance);
    			if($ret <= 0){
    				$this->{__CLASS__.'_model'}->rollback();
    				$this->error('创建钱包失败，请稍后重试');
    			}
    			$this->{__CLASS__.'_model'}->commit();
    			 
    			
    			break;
    		case 'Pwd':
    			$count = -1;
    			$userData = $this->user_model->retrieve($count, NULL, NULL, NULL, array('telephone'=>$input['Telephone']));
    			
    			if(empty($userData) || count($userData) != 1){
    				$this->error('用户不存在', self::STATUS_CODE_ERR);
    			}
    			$userData = &$userData[0];
    			$salt		= substr(uniqid(rand()), -6);
    			$password	= md5(md5($input['Password']).$userData['salt']);
    			
    			$userData->salt		= $salt;
    			$userData->password	= $password;
    			$ret = $this->user_model->SaveUserInfo(object_to_array($userData));
    			if($ret < 0){
    				$this->error('保存失败，请重新修改');
    			}

    			break;
    		default:
    			$this->error('错误的消息类型！');
    	}
    	
    	//注册成功生成token
    	$count = -1;
    	$userData = $this->user_model->retrieve($count, NULL, NULL, NULL, array('username'=>$userData['username']));
    	$userData = &$userData[0];
    	$userBalanceData = $this->User_balance_model->retrieve($count, NULL, NULL, NULL, array('uid'=>$userData->id));
    	$userBalanceData = &$userBalanceData[0];
    	$this->session->sess_create();
    	$this->load->driver('cache', array('adapter' => 'redis'));
    	
    	$cache = $this->cache->get('user_'.$userData->id);
    	if(empty($cache)){
    		$this->cache->save('user_'.$userData->id, $userData);
    	}
    	
    	$this->session->set_userdata(array(
    			'uid'		=> $userData->id,
    			'telephone'		=> $userData->telephone,
    			'nickname'	=> $userData->nickname,
    			'uname'		=> $userData->username
    	));

    	$this->load->model('User_msg_model');
    	$msgs = $this->User_msg_model->getMsgs($this->session->userdata('uid'));
    	if(!empty($msgs)){
    		$msgs = object_to_array($msgs);
    		$msgCount = count($msgs);
    	} else{
    		$msgCount = 0;
    	}
    	//返回结果
    	$results = array(
			'Token'		=> $this->session->userdata('session_id'),
    		'UserID'	=> $this->session->userdata('uid'),
    		'Username'	=> $this->session->userdata('uname'),
    		'Telephone'	=> $this->session->userdata('telephone'),
    		'HeadPortrait'	=> $userData->headportrait,
    		'CarNo'			=> $userData->car_no,
    		'Balance'		=> $userBalanceData->amount,
    		'CouponCount'	=> '0',
    		'MsgCount'		=> $msgCount
    	);
    	$this->success($results, '注册成功！');
    }
    
	
    /**
     * 用户手机注册码获取接口
     * 
     * 页面	:用户注册页面1、找回密码页面
     * URL	:/user/getauthcode
     * 备注	:注册时会检测手机号唯一性（type:Reg注册；Pwd找回密码）
     * 验证	:否
     * 接受参数:Telephone，Type(Reg/Pwd)
     * 返回参数:
     */
    function getauthcode(){
    	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	if(count($input) != 2 || !isset($input['Telephone']) || !isset($input['Type'])){
    		$this->error('接口参数不正确！');
    	}
    	//初始化
    	!$input['Telephone'] &&	($input['Telephone'] = $this->varFilter->checkString($input['Telephone']));
    	if(empty($input['Telephone'])){
    		$this->error('手机号码不能为空，请重新输入');
    	}
    	if(!checkValid4Phome($input['Telephone'])){
    		$this->error('手机号码非法，请重新输入');
    	}
    	if(!in_array($input['Type'], array('Reg', 'Pwd'))){
    		$this->error('参数类型不正确，请重新输入');
    	}
    	
    	//业务逻辑
    	switch ($input['Type']){
    		case 'Reg':
    			$count = 1;
    			$ret = $this->user_model->retrieve($count, NULL, NULL, NULL, array('telephone'=>$input['Telephone']));
    			if($ret != 0) {
    				$this->error('您输入的手机号已存在！');
    			}
    			break;
    			
    		case 'Pwd':
    			$count = 1;
    			$ret = $this->user_model->retrieve($count, NULL, NULL, NULL, array('telephone'=>$input['Telephone']));
    			if($ret != 1) {
    				$this->error('您输入的手机号不存在！');
    			}
    			break;
    			
    		default:
    			$this->error('错误的消息类型！');
    	}
    	
    	//生成随机验证码
    	$code = '123456';//substr(uniqid(rand()), -6);
    	$count = $this->session->setAuthCode($input['Telephone'],$input['Type'],$code);
    	if($count > 100) {
    		$this->error('请求过于频繁');
    	}
		//调取短信平台SDK

    	
    	
    	//返回结果
    	$this->success($results);
    }

    /**
     * 用户手机注册码检测接口
     *
     * 页面	:用户注册页面2、找回密码页面
     * URL	:/user/checkauthcode
     * 备注	:
     * 验证	:否
     * 接受参数:Authcode，Telephone,Type
     * 返回参数:
     */
    function checkauthcode(){
    	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
     	if(count($input) != 3 || !isset($input['Authcode']) || !isset($input['Telephone']) || !isset($input['Type'])){
     		$this->error('接口参数不正确！');
     	}
	   	//初始化
    	if(empty($input['Authcode']) || strlen($input['Authcode']) != 6){
    		$this->error('您输入的验证码不正确！');
    	}
    	
    	if(!in_array($input['Type'], array('Reg', 'Pwd'))){
    		$this->error('参数类型不正确，请重新输入');
    	}
		//检测验证码相同
    	$code = $this->session->getAuthCode($input['Telephone'], $input['Type']);
    	if(!$code) {
    		$this->error('未生成验证码或验证码已过期');
    	}
		if($input['Authcode'] != $code) {
			$this->error('您输入的验证码不正确！');
		}
		//$this->session->delAuthCode($input['Telephone'], $input['Type']);
		
		//返回结果
    	$this->success($results);
    }
    
//     /**
//      * 获取用户信息接口
//      *
//      * 页面	:个人中心
//      * URL	:/user/getuserinfo
//      * 备注	:
//      * 接受参数:
//      * 返回参数:Username,Telephone,HeadPortrait（头像url）,CarNo,Balance（余额），CouponCount（可用优惠券个数），MsgCount（消息个数）
//      */
//     function getuserinfo(){
//     	$this->checkToken();
//     	//初始化    	
//     	$data = $this->user_model->getUserInfo($this->session->userdata('uid'));    	
//     	//返回结果
//     	$this->success(object_to_array($data));
//     }
    
    /**
     * 修改用户信息接口
     *
     * 页面	:个人中心
     * URL	:/user/updateuserinfo
     * 备注	:
     * 验证	:是
     * 接受参数:Attribute(UserName,CarNo),Value
     * 返回参数:
     */
    function updateuserinfo(){
        //初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	$this->checkToken();
    	if(count($input) != 2 || !isset($input['Attribute']) || !isset($input['Value'])){
    		$this->error('接口参数不正确！');
    	}
    	$data = $this->user_model->getUserInfo($this->session->userdata('uid'));
    	if(empty($data)){
    		$this->error('用户不存在');
    	}
    	!$input['Value'] &&
    	($input['Value'] = $this->varFilter->checkString($input['Value']));
    	if(empty($input['Value'])){
    		$this->error('属性值不能为空');
    	}
    	switch ($input['Attribute']) {
    		case 'Username':
    	    	if(checkValid4Phome($input['Value'])){
		    		$this->error('不能使用手机号作为用户名');
		    	}
		    	$data->username	= $input['Value'];
    			break;
    		case 'CarNo':
    			$data->car_no	= $input['Value'];
    			break;
    		default:
    			$this->error('非法属性');
    	}
    	$ret = $this->user_model->SaveUserInfo(object_to_array($data));
    	if($ret < 0){
    		$this->error('保存失败，请重新修改');
    	}
    	
	   	//返回结果
    	$this->success();
    }
    
    /**
     * 修改用户头像接口
     *
     * 页面	:个人中心
     * URL	:/user/updateheadportrait
     * 备注	:
     * 验证	:是
     * 接受参数:File（base64的图片）
     * 返回参数:HeadPortrait
     */
    function updateheadportrait(){
    	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	$this->checkToken();
    	if(count($input) != 1 || !isset($input['File'])){
    		$this->apioutput->apiResponseError('接口参数不正确！');
    	}
    	if(empty($input['File'])){
    		$this->apioutput->apiResponseError('上传文件不能为空');
    	}

    	//业务逻辑
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $input['File'], $result)){
			$type = $result[2];
			if(empty($type) || !in_array(strtolower($type), array('jpg', 'jpeg', 'png'))){
				$this->apioutput->apiResponseError('头像格式不正确');
			}
			$path = dirname(BASEPATH).'/uploads/avatar/'.$this->mytoken->userdata('uid');
			
			if(!is_dir($path)){
				if(false == mkdirs($path)){
					$this->apioutput->apiResponseError('没有操作文件的权限');
				}
			}
			
			$filepath= $path.'/'.(microtime()*1000).$type;
			try{
    			@file_put_contents($filepath, base64_decode(str_replace($result[1], '', $input['File'])));
    			if(!file_exists($filepath)){
    				$this->apioutput->apiResponseError('文件保存失败');
    			}
    			
//     			if(exif_imagetype($filepath) == false){
//     				$this->error('图像文件非法');
//     			}
    			if(!getimagesize($filepath)){
    				$this->apioutput->apiResponseError('图像文件非法');
    			}
    			
    			$userData = $this->user_model->getUserInfo($this->mytoken->userdata('uid'));
    			if(empty($userData)){
    				$this->apioutput->apiResponseError('错误记录');
    			}
    			$old_file = $userData->headportrait;
    			$userData['headportrait'] = $filepath;
    			$ret = $this->user_model->updateInfo($this->mytoken->userdata('uid'), $userData);
    			if($ret > 0){
    				!empty($old_file) && file_exists($old_file) && (@unlink($userData));
    			}
			} catch (Exception $e) {
    			$this->apioutput->apiResponseError($e->getMessages());
    		}
    	} else{
    		$this->error('非法数据！');
    	}
    	//返回结果
    	$results = array(
    			'HeadPortrait'	=> $filepath,
    	);
    	$this->success('图片保存成功');
    }
    
    /**
     * 获取消息列表
     *
     * 页面	:消息列表页
     * URL	:/user/getmsglist
     * 备注	:默认时间倒序排序
     * 验证	:是
     * 接受参数:PageSize, CurPage
     * 返回参数:[{Id,Status,Title,Msg,CreatedAt},{},...]
     */
    function getmsglist(){
    	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	$this->checkToken();
    	if(count($input) != 2 || !isset($input['PageSize']) || !isset($input['CurPage'])){
    		$this->error('接口参数不正确！');
    	}
    	 
    	!empty($input['CurPage'])
    	&& $input['CurPage'] = $this->varFilter->checkInt($input['CurPage']);
    	if(empty($input['CurPage'])){
    		$input['CurPage'] = 1;
    	}
    	$input['CurPage'] -= 1;
    	!empty($input['PageSize'])
    	&& $input['PageSize'] = $this->varFilter->checkInt($input['PageSize']);
    	if(empty($input['PageSize'])){
    		$this->error('参数异常');
    	}
    	$this->load->model('User_msg_model');
    	$msgStatuses = $this->User_msg_model->getStatuses();
    	$msgs = $this->User_msg_model->getMsgs($this->session->userdata('uid'), NULL, $input['CurPage'], $input['PageSize']);
    	if(!empty($msgs)){
    		$msgs = object_to_array($msgs);
    		foreach ($msgs as $msgData){
    			$msg = array(
    					'Id'				=> $msgData['id'],
    					'Status'			=> $msgStatuses[$msgData['status']],//取消
    					'Title'				=> $msgData['title'],
    					'Msg'				=> $msgData['msg'],
    					'CreatedAt'			=> $msgData['created_at']
    			);
    			array_push($results, $msg);
    		}
    	}
    	//返回结果
    	$this->success($results);
    }
    
    
    /**
     * 用户获取通知列表接口
     *
     * 页面	:登陆页面
     * URL	:/message/getinformlist
     * 备注	:
     * 验证	:是
     * 接受参数:PageSize, CurPage
     * 返回参数:[{Id,Status,Title,Msg,CreatedAt},{},...]
     */
    public function getuserdynamic(){
    	//初始化
    	$input = $this->input->post();
    	$results = array();
    	//检测参数及授权合法性
    	$this->checkToken();
    	if(count($input) != 2 || !isset($input['PageSize']) || !isset($input['CurPage'])){
    		$this->apioutput->apiResponseError('接口参数不正确！');
    	}
    	 
    	!empty($input['CurPage'])
    	&& $input['CurPage'] = $this->varfilter->checkInt($input['CurPage']);
    	if(empty($input['CurPage'])){
    		$input['CurPage'] = 1;
    	}
    	$input['CurPage'] -= 1;
    	!empty($input['PageSize'])
    	&& $input['PageSize'] = $this->varfilter->checkInt($input['PageSize']);
    	if(empty($input['PageSize'])){
    		$this->apioutput->apiResponseError('参数异常');
    	}
    	 
    	$data = $this->user_concern_model->getConcerned($this->mytoken->userdata('uid'));
    	foreach ($data as $row){
    		$concernedArr[] = $row['concern_id'];
    	}
    	$data = $this->user_dynamic_model->getDynamic($concernedArr, $input['PageSize'], $input['PageSize']*$input['CurPage']);
    	
    	foreach ($data as $row){
    		$uInfo  = $this->user_model->getInfo($row['user_id']);
    		$hintArr = array(
    				1	=>	'发表了话题',
    				2	=>	'评论了话题',
    				3	=>	'加入了圈子',
    		);
    		$urlArr = array(
    				1	=>	'topic',
    				2	=>	'topic',
    				3	=>	'circle',
    		);
    		switch ($row['type']){
    			case 1:
    			case 2:
    				$objInfo	= $this->topic_model->getInfo($row['obj_id']);
    				$commentsNumber = $objInfo['comments_number'];
    				break;
    			case 3:
    				$commentsNumber = '';
    				break;
    			default:
    				break;
    		}
    			
    		$results[] = array(
    				'Avatar'		=>	site_url($uInfo['headportrait']),
    				'Name'			=>	isset($uInfo['nickname'])?$uInfo['nickname']:'',
    				'Hint'			=>	isset($hintArr[$row['type']])?$hintArr[$row['type']]:'',
    				'Title'			=>	$row['title'],
    				'ObjId'			=>	$row['obj_id'],
    				'ObjType'		=>	isset($urlArr[$row['type']])?$urlArr[$row['type']]:'',
    				'CommentsNumber'=>	$commentsNumber,
    				'Content'		=>	$row['content'],
    				'CircleName'		=>	$row['circle_name'],
    				'Datetime'			=>	$this->user_dynamic_model->getTimeFormat(strtotime($row['created_at']))
    		);
    	}
    	//返回结果
    	$this->apioutput->apiResponseSuccess($results);
    }
}